//
//  WB_MessageManager.m
//  GhStaff
//
//  Created by mini3 on 2017/12/7.
//  Copyright © 2017年 GhStaff. All rights reserved.
//

#import "WB_MessageManager.h"

@interface WB_MessageManager()
///http请求管理
@property (nonatomic, strong) WB_HttpManager *httpManager;

///请求Id
@property (nonatomic, assign) NSInteger overallRequestId;

///不提示网络错误请求集合
@property(nonatomic, strong) NSMutableSet *unNoticeNetworkErrorSet;

///不跳转登录请求集合
@property(nonatomic, strong) NSMutableSet *unToLoginSet;

///请求参数缓存
@property(nonatomic, strong) NSMutableDictionary *requestParamCache;

///当前请求id
@property(nonatomic, strong) NSString *currentRequestId;
@end


static WB_MessageManager *_messageManager = nil;

@implementation WB_MessageManager

@synthesize httpManager;

+ (WB_MessageManager *)shareMessageManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _messageManager = [[self alloc] init];
        _messageManager.httpManager = [[WB_HttpManager alloc] init];
        _messageManager.unNoticeNetworkErrorSet = [[NSMutableSet alloc] initWithCapacity:0];
        _messageManager.overallRequestId = 200000;
    });

    return _messageManager;
}


/// 请求数据 POST
- (NSString*)requestPostWithAction:(NSString *)action
                   dictionaryParam:(NSDictionary *)param
                   withResultBlock:(WBRequestResultBlock)resultBlock
{
    NSAssert(action, @"action must not be nil!");
    
    NSString *requestId = [self autoGetRequestId];
    NSString *url = [NSString stringWithFormat:@"%@%@",SERVER_TEST,action];
    //缓存请求参数
    if(resultBlock){
        [self.requestParamCache setObject:@[@(WBRequsetTypeOfNormal),action, param ? param : @{}, resultBlock] forKey:requestId];
    }
    
    [httpManager requestPostWithUrl:url dictionaryParam:param retquestId:requestId withResultBlock:^(NSString *requestId, NSString *code, NSString *message, id data) {
        if(resultBlock){
            resultBlock(code, message, data);
        }
    }];
    return requestId;
}



/// 请求数据 登录 注册  POST
- (NSString*)requestPostLoginRegWithAction:(NSString *)action
                           dictionaryParam:(NSDictionary *)param
                           withResultBlock:(WBRequestResultBlock)resultBlock
{
    NSAssert(action, @"action must not be nil!");
    
    NSString *requestId = [self autoGetRequestId];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",SERVER_TEST,action];
    
    
    //缓存请求参数
    if(resultBlock){
        [self.requestParamCache setObject:@[@(WBRequsetTypeOfNormal),action, param ? param : @{}, resultBlock] forKey:requestId];
    }
    
    [httpManager requestPostLoginRegWithUrl:url dictionaryParam:param retquestId:requestId withResultBlock:^(NSString *requestId, NSString *code, NSString *message, id data) {
        if(resultBlock){
            resultBlock(code, message, data);
        }
    }];
    
    return requestId;
}
/// 重置手机登录密码 PATCH
- (NSString*)requestPatchResetPwdWithAction:(NSString *)action
                            dictionaryParam:(NSDictionary *)param
                            withResultBlock:(WBRequestResultBlock)resultBlock
{
    NSAssert(action, @"action must not be nil!");
    
    NSString *requestId = [self autoGetRequestId];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",SERVER_TEST,action];
    
    //缓存请求参数
    if(resultBlock){
        [self.requestParamCache setObject:@[@(WBRequsetTypeOfNormal),action, param ? param : @{}, resultBlock] forKey:requestId];
    }
    
    [httpManager requestPatchResetPwdWithUrl:url dictionaryParam:param retquestId:requestId withResultBlock:^(NSString *requestId, NSString *code, NSString *message, id data) {
        if(resultBlock){
            resultBlock(code, message, data);
        }
    }];
    
    return requestId;
}

/// 请求数据 GET
- (NSString *)requestGetWithAction:(NSString *)action
                   dictionaryParam:(NSDictionary *)param
                   withResultBlock:(WBRequestResultBlock)resultBlock
{
    NSAssert(action, @"action must not be nil!");
    
    NSString *requestId = [self autoGetRequestId];
    
    NSString *url = [NSString stringWithFormat:@"%@",action];
    
    //缓存请求参数
    if(resultBlock){
        [self.requestParamCache setObject:@[@(WBRequsetTypeOfNormal),action, param ? param : @{}, resultBlock] forKey:requestId];
    }
    
    [httpManager requestGetWithUrl:url dictionaryParam:param retquestId:requestId withResultBlock:^(NSString *requestId, NSString *code, NSString *message, id data) {
        if(resultBlock){
            resultBlock(code, message, data);
        }
    }];
    
    return requestId;
}


///请求活动数据  GET
//- (NSString *)requestActivityGetWithAction:(NSString *)action
//                           dictionaryParam:(NSDictionary *)param
//                           withResultBlock:(WBRequestResultBlock)resultBlock
//{
//    NSAssert(action, @"action must not be nil!");
//    
//    NSString *requestId = [self autoGetRequestId];
//    
//    NSString *url = [NSString stringWithFormat:@"%@%@",ACTIVITY_SERVER,action];
//    
//    //缓存请求参数
//    if(resultBlock){
//        [self.requestParamCache setObject:@[@(WBRequsetTypeOfNormal),action, param ? param : @{}, resultBlock] forKey:requestId];
//    }
//    
//    [httpManager requestGetWithUrl:url dictionaryParam:param retquestId:requestId withResultBlock:^(NSString *requestId, NSString *code, NSString *message, id data) {
//        if(resultBlock){
//            resultBlock(code, message, data);
//        }
//    }];
//    
//    return requestId;
//}


#pragma mark --------- private

///自动获取请求id
-(NSString*)autoGetRequestId
{
    if(self.overallRequestId > 299999){
        self.overallRequestId = 200000;
    }
    self.overallRequestId++;
    
    return [NSString stringWithFormat:@"%ld", (long)self.overallRequestId];
}


///显示网络连接错误
-(void)showNetworkErrorNotice:(NSString*)errCode
                       errMsg:(NSString*)errMsg
                    requestId:(NSString*)requestId
{
    if(([errCode isEqualToString:@"-2"] || [errCode isEqualToString:@"-1009"])){
        
        if([self.unNoticeNetworkErrorSet containsObject:requestId]){
            [self.unNoticeNetworkErrorSet removeObject:requestId];
            return;
        }
        
        [DATAMODEL.alertManager showNetworkErrorMessage:errMsg];
        [DATAMODEL.alertManager setActionEventBoloc:^(NSInteger buttonIndex) {
            if(buttonIndex == 0){
                
            }
        }];
        errMsg = @"";
    }else if([errCode isEqualToString:@"1000"] || [errCode isEqualToString:@"1001"]){ // 需要登录/在其他地方登录
        
        if([self.unToLoginSet containsObject:requestId]){
            [self.unToLoginSet removeObject:requestId];
            return;
        }
        
        if (!self.isToLogin) {
            self.isToLogin = YES;
            self.currentRequestId = requestId;
            // 0.5秒后执行（在iOS7上，不能在viewLoad中pushViewController，要在viewDidAppear中）
            [self performSelector:@selector(pushSecondController) withObject:nil afterDelay:0.5f];
        }
    }else{
        [self.requestParamCache removeAllObjects];
        self.currentRequestId = @"";
    }
    
    [self.unNoticeNetworkErrorSet removeObject:requestId];
    [self.unToLoginSet removeObject:requestId];
}

- (void) pushSecondController
{
    if(self.loginVc){
        [self.loginVc didReceiveMemoryWarning];
        
        UIViewController * currentVC = [[Hen_Util getInstance] getCurrentViewController];
        [currentVC.navigationController pushViewController:self.loginVc animated:YES];
    }
}

///重新请求
-(void)reRequst
{
    NSMutableArray *array = self.requestParamCache[self.currentRequestId];
    if(array.count > 0){
        WBRequsetType type = [((NSNumber*)array.firstObject) integerValue];
        if(type == WBRequsetTypeOfNormal){
            [self requestPostWithAction:array[1] dictionaryParam:array[2] withResultBlock:array[3]];
        }
    }
    [self.loginVc didReceiveMemoryWarning];
}


///添加不提示网络错误请求
-(void)addUnNoticeNetworkErrorRequestId:(NSString*)requestId
{
    [self.unNoticeNetworkErrorSet addObject:requestId];
}

///添加不跳转登录请求
-(void)addUnToLoginRequestId:(NSString*)requestId
{
    [self.unToLoginSet addObject:requestId];
}

#pragma mark -- getter, setter


-(NSMutableDictionary*)requestParamCache
{
    if(!_requestParamCache){
        _requestParamCache = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _requestParamCache;
}


@end
